package commons.template;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.util.ResourceUtils;

import freemarker.template.Configuration;
import freemarker.template.DefaultObjectWrapper;
import freemarker.template.Template;
import freemarker.template.TemplateException;

/**
 * generate template factory
 * 
 * @author jkyang
 * 
 */
public class FtlTemplate {

	private static Log log = LogFactory.getLog(FtlTemplate.class);

	private static Configuration cfg;

	private static void init() {
		cfg = new Configuration();
		try {
			File f = ResourceUtils.getFile("classpath:commons/template");
			log.debug(f.getPath());
			cfg.setDirectoryForTemplateLoading(f);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		cfg.setObjectWrapper(new DefaultObjectWrapper());
	}

	@SuppressWarnings("unchecked")
	public static String getTemplate(String fileName, Map root) {
		if (cfg == null) {
			init();
		}
		StringWriter out = new StringWriter();
		try {
			Template temp = cfg.getTemplate(fileName);
			temp.process(root, out);
			out.flush();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (TemplateException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return out.toString();
	}

	@SuppressWarnings("unchecked")
	public static void main(String[] args) {
		Map root = new HashMap();
		root.put("test", "<ddtestd>");
		String name = FtlTemplate.getTemplate("test.ftl", root);
		System.out.println(name);
	}

}
